package demo.android.myapplication.demos;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.TextureView;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import demo.android.myapplication.R;

/**
 * <br>createBy Gw
 * <br>createTime: 2021/7/19 15:35
 */
public class LiveCameraActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener {

	private TextureView mTextureView;
	private SurfaceTexture mSurface;
	private Camera mCamera;

	@Override
	protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_live_camera);
		mTextureView = findViewById(R.id.surface);
		mTextureView.setSurfaceTextureListener(this);
	}

	@Override
	public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
		mSurface = surface;
		ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 100);
	}

	@Override
	public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {

	}

	@Override
	public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
		mCamera.stopPreview();
		mCamera.release();
		return true;
	}

	@Override
	public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {

	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
			mCamera = Camera.open();
			try {
				mCamera.setPreviewTexture(mSurface);
				mCamera.startPreview();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}